package org.fu.crowd.utils;

import org.fu.crowd.constant.CrowdConstant;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 通用工具方法类
 */
public class CrowdUtils {

    /**
     * 判断当前请求是否为ajax请求
     * @param request
     * @return
     */
    public static boolean judgeRequestType(HttpServletRequest request){
        //获取请求消息头
        String header = request.getHeader("X-Requested-With");

        return header!=null&&header.contains("XMLHttpRequest");
    }


    /**
     *  MD5加密算法
     */
    public static String md5(String source){
        if (source==null||source.length()==0){
            throw new RuntimeException(CrowdConstant.MESSAGE_STRING_INVALIDATE);
        }

        try {
            String algorithm= "md5";
            MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
            byte[] input = source.getBytes();
            byte[] output = messageDigest.digest(input);
            int sigNum = 1;
            BigInteger bigInteger = new BigInteger(sigNum,output);
            //转化成16进制
            int radix = 16;
            String encoded = bigInteger.toString(radix).toUpperCase();

            return encoded;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
